<template>
  <div class="carousel-container" ref="carouselContainer">
    <el-carousel
      v-model:current-index="currentIndex"
      :autoplay="true"
      :interval="5000"
      arrow="hover"
      :height="imgHeight">
      <el-carousel-item v-for="item in carouselItems" :key="item.id">
        <div class="carousel-item-wrapper" @click="handleCarouselClick(item)">
          <img :src="item.image" :alt="item.alt" class="carousel-image" />
        </div>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, nextTick } from 'vue';
  import { ElCarousel, ElCarouselItem } from 'element-plus';
  import 'element-plus/dist/index.css';
  import { useRouter } from 'vue-router';
  import { FeedsAPI } from '@/api/feeds';
  import { AiAPI } from '@/api/ai';

  const router = useRouter();

  const podItem = ref();
  const getProducts = async () => {
    const { data } = await AiAPI.genProductTemplates();
    podItem.value = data[0] || {};
  };

  // 轮播图数据
  const carouselItems = ref([
    {
      id: 1,
      image: 'https://imgs.nexbie.com/uploads/f8017a9daeaa40bd97035ca2933ea61e.webp',
      alt: 'Design Image 1',
      path: `/productDetail`,
    },
    // {
    //   id: 2,
    //   image: 'https://imgs.nexbie.com/uploads/75b4a6e119f046e78f7c64a3150125f4.webp',
    //   alt: 'Design Image 2',
    // },
    {
      id: 3,
      image: 'https://imgs.nexbie.com/uploads/d3b2647922034935a0aa4a33b6d6e2af.jpg',
      alt: 'Design Image 3',
      aid: 1002,
    },
  ]);

  // 处理轮播图点击事件
  const handleCarouselClick = (item: any) => {
    // 检查是否满足条件：aid=1002 且有path
    if (item.aid) {
      router.push({
        path: '/contest/detail',
        query: {
          aid: item.aid,
        },
      });
    } else if (item.path) {
      if (item.path.includes('productDetail')) {
        router.push({
          path: item.path,
          query: {
            product_id: podItem.value?.product_id || '',
            template_id: podItem.value?.template_id || '',
          },
        });
      } else {
        router.push(item.path);
      }
    }
    // 如果没有path，则不执行跳转
  };

  // 当前轮播图索引
  const currentIndex = ref(0);
  // 图片高度
  const imgHeight = ref('auto');
  // 图片宽高比
  const aspectRatio = ref(594 / 200); // 默认宽高比，将在图片加载后更新
  // 容器引用
  const carouselContainer = ref<HTMLElement>();
  // ResizeObserver实例
  let resizeObserver: ResizeObserver | null = null;

  // 简易防抖函数
  const debounce = (fn: (...args: any[]) => void, delay = 120) => {
    let timer: number | null = null;
    return (...args: any[]) => {
      if (timer) window.clearTimeout(timer);
      timer = window.setTimeout(() => {
        fn(...args);
        timer = null;
      }, delay);
    };
  };

  // 计算图片高度
  const calculateImageHeight = () => {
    if (!carouselContainer.value) return;

    const containerWidth = carouselContainer.value.offsetWidth;
    // 根据容器宽度和宽高比计算高度
    // const height = Math.round(containerWidth / aspectRatio.value);
    // 修改后
    const height = Math.round(containerWidth / aspectRatio.value);
    imgHeight.value = `${height}px`;
    //同步左边节点高度
    document.querySelector('.ai-creater-container')?.setAttribute('style', `height: ${height}px`);
  };

  // 防抖处理的计算函数
  const debouncedCalculateHeight = debounce(calculateImageHeight, 120);

  // 生命周期
  onMounted(() => {
    getProducts();
    nextTick(() => {
      // 添加窗口resize事件监听
      window.addEventListener('resize', debouncedCalculateHeight);

      // 使用ResizeObserver监听容器大小变化（更精确）
      if ('ResizeObserver' in window && carouselContainer.value) {
        resizeObserver = new ResizeObserver(debouncedCalculateHeight);
        resizeObserver.observe(carouselContainer.value);
      }
    });
  });

  onUnmounted(() => {
    // 清理事件监听和ResizeObserver
    window.removeEventListener('resize', debouncedCalculateHeight);
    if (resizeObserver) {
      resizeObserver.disconnect();
      resizeObserver = null;
    }
  });
</script>

<style scoped lang="scss">
  .carousel-container {
    flex: 1;
    border-radius: 8px;
    overflow: hidden;
    min-width: 594px;
  }

  .carousel-item-wrapper {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    cursor: pointer;
    position: relative; // 新增：设置为相对定位，使伪元素可以绝对定位
  }

  // 新增：使用::after伪元素添加底部遮罩层
  .carousel-item-wrapper::after {
    content: ''; // 伪元素必须有content属性
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 10%;
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.25) 100%);
    pointer-events: none; // 确保遮罩层不影响点击事件
    z-index: 10; // 确保遮罩层在图片之上
  }

  .carousel-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    border-radius: 8px;
    overflow: hidden;
  }
  :deep(.el-carousel__indicator) {
    margin-bottom: -4px;
  }
  :deep(.el-carousel__button) {
    width: 20px;
    height: 4px;
    border-radius: 5px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.el-carousel__arrow) {
    background-color: rgba(0, 0, 0, 0.32);
    width: 40px;
    height: 40px;
    transition: all 0.3s ease;
    &:hover {
      background-color: rgba(0, 0, 0, 0.56);
    }
    .el-icon {
      width: 20px;
      height: 20px;
    }
    .el-icon svg {
      width: 20px;
      height: 20px;
    }
  }
</style>
